#!/bin/bash
# deploy.sh - JFastFiler 一键部署脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查系统要求
check_requirements() {
    log_info "检查系统要求..."
    
    # 检查操作系统
    if [[ -f /etc/os-release ]]; then
        source /etc/os-release
        log_info "检测到操作系统: $NAME $VERSION"
    else
        log_warning "无法检测操作系统版本"
    fi
    
    # 检查Go是否安装
    if ! command -v go &> /dev/null; then
        log_error "Go未安装，请先安装Go 1.21+"
        exit 1
    fi
    
    # 检查Go版本
    GO_VERSION=$(go version | awk '{print $3}' | sed 's/go//')
    REQUIRED_GO="1.21"
    if [ "$(printf '%s\n' "$REQUIRED_GO" "$GO_VERSION" | sort -V | head -n1)" = "$REQUIRED_GO" ]; then
        log_success "Go版本满足要求: $GO_VERSION"
    else
        log_error "Go版本过低，需要1.21+，当前版本: $GO_VERSION"
        exit 1
    fi
    
    # 检查内存
    MEM_KB=$(grep MemTotal /proc/meminfo | awk '{print $2}')
    MEM_GB=$((MEM_KB / 1024 / 1024))
    if [ $MEM_GB -lt 2 ]; then
        log_warning "内存不足2GB，建议增加内存"
    else
        log_success "内存充足: ${MEM_GB}GB"
    fi
    
    # 检查磁盘空间
    DISK_SPACE=$(df . | awk 'NR==2 {print $4}')
    DISK_SPACE_GB=$((DISK_SPACE / 1024 / 1024))
    if [ $DISK_SPACE_GB -lt 10 ]; then
        log_error "磁盘空间不足10GB"
        exit 1
    else
        log_success "磁盘空间充足: ${DISK_SPACE_GB}GB"
    fi
}

# 安装系统依赖
install_dependencies() {
    log_info "安装系统依赖..."
    
    if command -v apt-get &> /dev/null; then

        # Ubuntu/Debian
        sudo apt-get update
        sudo apt-get install -y \
            sqlite3 \
            libimage-exiftool-perl \
            imagemagick \
            ghostscript \
            clamav \
            clamav-daemon \
            libreoffice \
            antiword \
            catdoc \
            p7zip-full \
            curl \
            wget \
            git
        
    elif command -v yum &> /dev/null; then
        # CentOS/RHEL
        sudo yum install -y \
            sqlite \
            perl-Image-ExifTool \
            ImageMagick \
            ghostscript \
            clamav \
            clamav-update \
            libreoffice \
            antiword \
            catdoc \
            p7zip \
            curl \
            wget \
            git
        
    elif command -v dnf &> /dev/null; then
        # Fedora
        sudo dnf install -y \
            sqlite \
            perl-Image-ExifTool \
            ImageMagick \
            ghostscript \
            clamav \
            clamav-update \
            libreoffice \
            antiword \
            catdoc \
            p7zip \
            curl \
            wget \
            git
    else
        log_warning "无法自动安装依赖，请手动安装所需软件包"
    fi
    
    # 启动ClamAV服务
    if command -v systemctl &> /dev/null; then
        sudo systemctl enable clamav-freshclam
        sudo systemctl start clamav-freshclam
        sudo freshclam  # 更新病毒库
    fi
}

# 创建目录结构
create_directories() {
    log_info "创建目录结构..."
    
    local base_dir="/opt/jfastfiler"
    local dirs=(
        "$base_dir"
        "$base_dir/bin"
        "$base_dir/config"
        "$base_dir/data"
        "$base_dir/storage"
        "$base_dir/temp"
        "$base_dir/previews"
        "$base_dir/logs"
        "$base_dir/backups"
        "$base_dir/scripts"
    )
    
    for dir in "${dirs[@]}"; do
        sudo mkdir -p "$dir"
        sudo chmod 755 "$dir"
    done
    
    # 设置存储目录权限
    sudo chmod 750 "$base_dir/storage"
    sudo chmod 750 "$base_dir/data"
    sudo chmod 777 "$base_dir/temp"
    sudo chmod 777 "$base_dir/previews"
    
    log_success "目录结构创建完成"
}

# 下载源代码
download_source() {
    log_info "下载源代码..."
    
    local repo_url="https://github.com/jfastfiler/jfastfiler.git"
    local temp_dir="/tmp/jfastfiler-source"
    
    if [ -d "$temp_dir" ]; then
        sudo rm -rf "$temp_dir"
    fi
    
    git clone "$repo_url" "$temp_dir"
    
    if [ $? -ne 0 ]; then
        log_error "代码下载失败"
        exit 1
    fi
    
    # 复制文件到安装目录
    sudo cp -r "$temp_dir/"* "/opt/jfastfiler/"
    sudo rm -rf "$temp_dir"
    
    log_success "源代码下载完成"
}

# 构建应用
build_application() {
    log_info "构建应用程序..."
    
    cd /opt/jfastfiler
    
    # 下载依赖
    go mod download
    
    # 构建
    go build -o bin/jfastfiler cmd/server/main.go
    
    if [ $? -ne 0 ]; then
        log_error "构建失败"
        exit 1
    fi
    
    # 设置可执行权限
    sudo chmod +x bin/jfastfiler
    
    log_success "应用程序构建完成"
}

# 创建配置文件
create_config() {
    log_info "创建配置文件..."
    
    local config_file="/opt/jfastfiler/config/config.yaml"
    
    # 生成随机密钥
    local jwt_secret=$(openssl rand -base64 32)
    local encryption_key=$(openssl rand -base64 32)
    
    cat > /tmp/config.yaml << EOF
server:
  host: "0.0.0.0"
  port: 8080
  mode: "release"
  upload_limit: 10737418240
  cors_origins: ["http://localhost:3000", "http://127.0.0.1:3000"]

database:
  path: "/opt/jfastfiler/data/filemanager.db"
  max_conn: 100
  idle_conn: 10
  conn_lifetime: 3600

storage:
  root_path: "/opt/jfastfiler/storage"
  temp_path: "/opt/jfastfiler/temp"
  max_file_size: 10737418240
  enable_encryption: true
  encryption_key: "$encryption_key"

cache:
  enabled: true
  size: 1000
  ttl: 300

security:
  jwt_secret: "$jwt_secret"
  token_expire: 3600
  bcrypt_cost: 10
  enable_2fa: false
  session_timeout: 7200
  
  virus_scan:
    enable: true
    clamav_host: "localhost"
    clamav_port: 3310
    scan_timeout: 30
  
  watermark:
    enable: true
    text: "JFastFiler - %username% - %datetime%"
    opacity: 0.3
    font_size: 20

preview:
  max_workers: 4
  image_quality: 80
  document_timeout: 30
  max_preview_size: 104857600
  
  libreoffice:
    enable: true
    path: "/usr/lib/libreoffice/program/soffice"
    timeout: 60

search:
  enable_content_search: true
  max_content_size: 10485760
  index_path: "/opt/jfastfiler/data/search_index"
  batch_size: 1000

logging:
  level: "info"
  file: "/opt/jfastfiler/logs/jfastfiler.log"
  max_size: 100
  max_backups: 10
  max_age: 30
  compress: true

monitoring:
  enable_metrics: true
  prometheus_port: 9090
  health_check_interval: 30
EOF

    sudo mv /tmp/config.yaml "$config_file"
    sudo chmod 600 "$config_file"
    
    log_success "配置文件创建完成"
}

# 初始化数据库
init_database() {
    log_info "初始化数据库..."
    
    cd /opt/jfastfiler
    
    # 运行数据库初始化脚本
    ./scripts/init_db.sh
    
    if [ $? -ne 0 ]; then
        log_error "数据库初始化失败"
        exit 1
    fi
    
    log_success "数据库初始化完成"
}

# 创建系统服务
create_systemd_service() {
    log_info "创建系统服务..."
    
    local service_file="/etc/systemd/system/jfastfiler.service"
    
    cat > /tmp/jfastfiler.service << EOF
[Unit]
Description=JFastFiler - High Performance File Management System
Documentation=https://github.com/jfastfiler/jfastfiler
After=network.target

[Service]
Type=simple
User=jfastfiler
Group=jfastfiler
WorkingDirectory=/opt/jfastfiler
ExecStart=/opt/jfastfiler/bin/jfastfiler
ExecReload=/bin/kill -HUP \$MAINPID
Restart=on-failure
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=jfastfiler

# 安全设置
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/opt/jfastfiler/storage /opt/jfastfiler/data /opt/jfastfiler/temp /opt/jfastfiler/previews /opt/jfastfiler/logs

# 资源限制
LimitNOFILE=65536
LimitNPROC=4096

[Install]
WantedBy=multi-user.target
EOF

    sudo mv /tmp/jfastfiler.service "$service_file"
    sudo chmod 644 "$service_file"
    
    log_success "系统服务创建完成"
}

# 创建专用用户
create_user() {
    log_info "创建专用用户..."
    
    if id "jfastfiler" &>/dev/null; then
        log_info "用户 jfastfiler 已存在"
    else
        sudo useradd -r -s /bin/false -d /opt/jfastfiler jfastfiler
        log_success "用户 jfastfiler 创建完成"
    fi
    
    # 设置目录所有权
    sudo chown -R jfastfiler:jfastfiler /opt/jfastfiler
    sudo chmod 750 /opt/jfastfiler
    
    log_success "用户权限设置完成"
}

# 配置防火墙
configure_firewall() {
    log_info "配置防火墙..."
    
    if command -v ufw &> /dev/null; then
        # Ubuntu
        sudo ufw allow 8080/tcp
        sudo ufw allow 9090/tcp
        log_success "UFW防火墙配置完成"
    elif command -v firewall-cmd &> /dev/null; then
        # CentOS/Fedora
        sudo firewall-cmd --permanent --add-port=8080/tcp
        sudo firewall-cmd --permanent --add-port=9090/tcp
        sudo firewall-cmd --reload
        log_success "FirewallD配置完成"
    else
        log_warning "未检测到支持的防火墙，请手动开放端口8080和9090"
    fi
}

# 启动服务
start_service() {
    log_info "启动服务..."
    
    sudo systemctl daemon-reload
    sudo systemctl enable jfastfiler
    sudo systemctl start jfastfiler
    
    # 等待服务启动
    sleep 5
    
    # 检查服务状态
    if sudo systemctl is-active --quiet jfastfiler; then
        log_success "JFastFiler服务启动成功"
    else
        log_error "服务启动失败"
        sudo systemctl status jfastfiler
        exit 1
    fi
}

# 健康检查
health_check() {
    log_info "执行健康检查..."
    
    # 等待服务完全启动
    sleep 10
    
    local max_retries=30
    local retry_count=0
    
    while [ $retry_count -lt $max_retries ]; do
        if curl -f http://localhost:8080/api/v1/health > /dev/null 2>&1; then
            log_success "健康检查通过"
            return 0
        fi
        
        retry_count=$((retry_count + 1))
        sleep 2
    done
    
    log_error "健康检查失败，服务未正常启动"
    return 1
}

# 显示部署信息
show_deploy_info() {
    log_success "=== JFastFiler 部署完成 ==="
    echo ""
    echo "服务信息:"
    echo "  - 访问地址: http://$(hostname -I | awk '{print $1}'):8080"
    echo "  - API文档: http://$(hostname -I | awk '{print $1}'):8080/swagger/index.html"
    echo "  - 监控指标: http://$(hostname -I | awk '{print $1}'):9090/metrics"
    echo ""
    echo "管理命令:"
    echo "  - 启动服务: sudo systemctl start jfastfiler"
    echo "  - 停止服务: sudo systemctl stop jfastfiler"
    echo "  - 重启服务: sudo systemctl restart jfastfiler"
    echo "  - 查看状态: sudo systemctl status jfastfiler"
    echo "  - 查看日志: sudo journalctl -u jfastfiler -f"
    echo ""
    echo "默认管理员账户:"
    echo "  - 用户名: admin"
    echo "  - 密码: admin123"
    echo ""
    echo "重要目录:"
    echo "  - 配置文件: /opt/jfastfiler/config/config.yaml"
    echo "  - 数据文件: /opt/jfastfiler/data/"
    echo "  - 日志文件: /opt/jfastfiler/logs/"
    echo "  - 存储目录: /opt/jfastfiler/storage/"
    echo ""
}

# 主部署函数
main() {
    log_info "开始部署 JFastFiler..."
    
    # 检查是否以root运行
    if [ "$EUID" -ne 0 ]; then
        log_error "请使用sudo或以root用户运行此脚本"
        exit 1
    fi
    
    # 执行部署步骤
    check_requirements
    install_dependencies
    create_directories
    download_source
    build_application
    create_config
    create_user
    init_database
    create_systemd_service
    configure_firewall
    start_service
    health_check
    show_deploy_info
    
    log_success "JFastFiler 部署完成！"
}

# 执行主函数
main "$@"